package org.example.reducejoin;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;

import java.io.IOException;

public class TableMap extends Mapper<LongWritable, Text, Text, TableBean> {

    private String fileName;

    @Override
    protected void setup(Mapper<LongWritable, Text, Text, TableBean>.Context context) throws IOException, InterruptedException {
        FileSplit inputSplit = (FileSplit) context.getInputSplit();
        fileName = inputSplit.getPath().getName();
    }

    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, TableBean>.Context context) throws IOException, InterruptedException {
        if ((int)(key.get()) == 0) {
            return;
        }
        String line = value.toString();

        Text k = new Text();
        TableBean v = new TableBean();
        if (fileName.contains("order")) {
            String[] split = line.split(" ");

            k.set(split[1]);
            v.setId(split[0]);
            v.setPid(split[1]);
            v.setAmount(Integer.parseInt(split[2]));
            v.setPname("");
            v.setFlag("order");
        } else if (fileName.contains("pd")) {
            String[] split = line.split(" ");

            k.set(split[0]);
            v.setId("");
            v.setPid(split[0]);
            v.setAmount(0);
            v.setPname(split[1]);
            v.setFlag("pd");
        }

        context.write(k,v);
    }
}

